# -*-coding:utf-8-*-

from delegates.base import BaseDelegate
import json


class DgkDevicesDelegate(BaseDelegate):
    def on_pre_get_list(self, **kwargs):
        platform = kwargs['platform'] if 'platform' in kwargs else False
        if platform:
            result = {'$or': [
                {'module_vendor_id': self._uid},
                {'vendor_id': self._uid},
            ]}, None
        else:
            result = {'owner_id': self._uid}, None
        if 'device_id_like' in kwargs:
            device_id_like = kwargs['device_id_like']
            result[0].update(device_id={'$regex': device_id_like})
        return result

    def on_pre_get(self, **kwargs):
        projection = {'_id': 0}
        platform = kwargs.get('platform', False)
        if platform:
            result = {'$or': [
                {'module_vendor_id': self._uid},
                {'vendor_id': self._uid},
            ]}, projection
        else:
            result = {'owner_id': self._uid}, projection
        return result

    def on_per_list_item(self, item, **kwargs):
        return True

    def on_pre_update(self, **kwargs):
        # 在这里做 specifics 中字段做检查
        # 需要将 wpm_cls payload 写进 DB 以确认 device_ids 的正确性
        specifics = kwargs['specifics']
        return specifics

    def on_post_update(self, **kwargs):
        specifics = kwargs.get('specifics', None)
        if specifics is not None and 'wpm_cls' in specifics:
            device_ids = kwargs['device_ids']
            field_name = 'wpm_cls'
            payload = json.dumps(specifics[field_name])
            for device_id in device_ids:
                topic = 't/d/%s/n/%s' % (device_id, field_name)
                self._publish(topic, payload)
